package net.arvin.mobilebanksystem.fragment;

import java.io.File;
import java.util.Calendar;

import net.arvin.dao.ResponseHandler;
import net.arvin.mobilebanksystem.R;
import net.arvin.mobilebanksystem.activity.MainActivity;
import net.arvin.mobilebanksystem.activity.UserInfoActivity;
import net.arvin.model.User;
import net.arvin.service.UserService;
import net.arvin.utils.NetConnectionUtil;
import net.arvin.utils.PhotoUtil;
import net.arvin.utils.PreferenceUtils;
import net.arvin.view.AvatarSelectorDialog;
import net.arvin.view.InputDialog;
import net.arvin.view.NormalDialog.MyDialogListener;
import net.arvin.view.SexSelectorDialog;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;

@TargetApi(19)
@SuppressLint("SdCardPath")
public class SettingFragment extends Fragment implements OnClickListener {
	private static final int IMAGE_REQUEST_CODE = 0;
	private static final int IMAGE_REQUEST_CODE_KITKAT = 1;
	private static final int CAMERA_REQUEST_CODE = 2;
	private static final int RESULT_REQUEST_CODE = 3;

	private static final int RESULT_CANCELED = 0;
	private static final File PHOTO_DIR = new File("/sdcard/MobileBank");

	public static SettingFragment mSetting;

	private RelativeLayout avatarLayout;
	private RelativeLayout nicknameLayout;
	private RelativeLayout sexLayout;
	private RelativeLayout emailLayout;
	private RelativeLayout birthdayLayout;
	private RelativeLayout passwordLayout;

	private ImageView avatar;
	private TextView nickname_tv;
	private TextView sex_tv;
	private TextView birthday_tv;
	private TextView email_tv;

	private Button quitBtn;

	private User user = null;
	private boolean isChanged = false;
	private ResponseHandler mResponseHandler;

	private SexSelectorDialog sexDialog;
	private InputDialog nameDialog;
	private InputDialog emailDialog;
	private AvatarSelectorDialog avatarDialog;
	private File mCurrentPhotoFile;
	private String IMAGE_FILE_PATH = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_setting, null);
		init(view);
		return view;
	}

	private void init(View view) {
		initView(view);
		initDate();
		initListener();
		mSetting = this;
		this.user = JSON.parseObject(
				PreferenceUtils.getPreferUserJson(getActivity()), User.class);
	}

	private void initDate() {
		user = JSON.parseObject(
				PreferenceUtils.getPreferUserJson(getActivity()), User.class);
		nickname_tv.setText(user.getNickname());
		sex_tv.setText(user.getSex());
		birthday_tv.setText(user.getBirthday());
		email_tv.setText(user.getEmail());
		IMAGE_FILE_PATH = PreferenceUtils.getPreferAvatarPath(getActivity());
		if (IMAGE_FILE_PATH != null) {
			Bitmap photo = BitmapFactory.decodeFile(IMAGE_FILE_PATH);
			avatar.setImageBitmap(photo);
		}
	}

	private void initListener() {
		avatarLayout.setOnClickListener(this);
		nicknameLayout.setOnClickListener(this);
		sexLayout.setOnClickListener(this);
		emailLayout.setOnClickListener(this);
		birthdayLayout.setOnClickListener(this);
		passwordLayout.setOnClickListener(this);

		quitBtn.setOnClickListener(this);
	}

	private void initView(View view) {
		avatarLayout = (RelativeLayout) view.findViewById(R.id.avatarLayout);
		nicknameLayout = (RelativeLayout) view
				.findViewById(R.id.nicknameLayout);
		sexLayout = (RelativeLayout) view.findViewById(R.id.sexLayout);
		emailLayout = (RelativeLayout) view.findViewById(R.id.emailLayout);
		birthdayLayout = (RelativeLayout) view
				.findViewById(R.id.birthdayLayout);
		passwordLayout = (RelativeLayout) view
				.findViewById(R.id.passwordLayout);

		avatar = (ImageView) view.findViewById(R.id.avatar);
		nickname_tv = (TextView) view.findViewById(R.id.nickname);
		sex_tv = (TextView) view.findViewById(R.id.sex);
		email_tv = (TextView) view.findViewById(R.id.email);
		birthday_tv = (TextView) view.findViewById(R.id.birthday);

		quitBtn = (Button) view.findViewById(R.id.quitBtn);
	}

	private void userChanged() {
		isChanged = true;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.avatarLayout:
			showAvatarDialog();
			break;
		case R.id.nicknameLayout:
			showNameDialog();
			break;
		case R.id.sexLayout:
			showSexDialog();
			break;
		case R.id.emailLayout:
			showEmailDialog();
			break;
		case R.id.birthdayLayout:
			showDateDialog();
			break;
		case R.id.passwordLayout:
			MainActivity.mainActivity.setTitleTv("密码管理");
			MainActivity.mainActivity.switchContent(
					new ResetPSWFragment(false), false);
			break;
		case R.id.quitBtn:
			logout();
			break;
		}
	}

	private void showAvatarDialog() {
		avatarDialog = new AvatarSelectorDialog(getActivity(),
				R.style.MyDialog, new MyDialogListener() {

					@Override
					public void onClick(View view) {
						switch (view.getId()) {
						case R.id.dialog_btn_photo:
							choosePhotoFromGallery();
							avatarDialog.dismiss();
							break;
						case R.id.dialog_btn_camera:
							final String status = Environment
									.getExternalStorageState();
							if (status.equals(Environment.MEDIA_MOUNTED)) {
								choosePhotoFromTakePhoto();
							} else {
								Toast.makeText(getActivity(), "没有sd卡",
										Toast.LENGTH_SHORT).show();
							}
							avatarDialog.dismiss();
							break;
						case R.id.dialog_btn_cancel:
							avatarDialog.dismiss();
							break;
						}
					}
				});
		avatarDialog.show();
	}

	private void showEmailDialog() {
		emailDialog = new InputDialog(getActivity(), R.style.MyDialog,
				new MyDialogListener() {

					@Override
					public void onClick(View view) {
						switch (view.getId()) {
						case R.id.dialog_btn_ensure:
							email_tv.setText(emailDialog.getInputContent());
							user.setEmail(emailDialog.getInputContent());
							userChanged();
							emailDialog.dismiss();
							break;
						case R.id.dialog_btn_cancel:
							emailDialog.dismiss();
							break;
						}
					}
				});
		emailDialog.dialogTips = (TextView) emailDialog.getWindow()
				.findViewById(R.id.dialog_tips);
		emailDialog.dialogTips.setText("邮箱");
		emailDialog.inputContent = (EditText) emailDialog.getWindow()
				.findViewById(R.id.dialog_input);
		emailDialog.inputContent.setHint("输入邮箱");
		emailDialog.show();
	}

	private void showNameDialog() {
		nameDialog = new InputDialog(getActivity(), R.style.MyDialog,
				new MyDialogListener() {

					@Override
					public void onClick(View view) {
						switch (view.getId()) {
						case R.id.dialog_btn_ensure:
							nickname_tv.setText(nameDialog.getInputContent());
							user.setNickname(nameDialog.getInputContent());
							userChanged();
							nameDialog.dismiss();
							break;
						case R.id.dialog_btn_cancel:
							nameDialog.dismiss();
							break;
						}
					}
				});
		nameDialog.dialogTips = (TextView) nameDialog.getWindow().findViewById(
				R.id.dialog_tips);
		nameDialog.inputContent = (EditText) nameDialog.getWindow()
				.findViewById(R.id.dialog_input);
		nameDialog.dialogTips.setText("昵称");
		nameDialog.inputContent.setHint("输入昵称");
		nameDialog.show();
	}

	private void showDateDialog() {
		final DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {
			@Override
			public void onDateSet(final DatePicker datePicker, final int year,
					final int month, final int dayOfMonth) {
				birthday_tv
						.setText(year + "-" + (month + 1) + "-" + dayOfMonth);
				user.setBirthday(birthday_tv.getText().toString().trim());
				userChanged();
			}
		};
		int year = Calendar.getInstance().get(Calendar.YEAR);
		int month = Calendar.getInstance().get(Calendar.MONTH);
		int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
		String birthday = birthday_tv.getText().toString();
		int f = birthday.indexOf("-");
		int e = birthday.lastIndexOf("-");
		year = Integer.parseInt(birthday.substring(0, f));
		month = Integer.parseInt(birthday.substring(f + 1, e)) - 1;
		day = Integer.parseInt(birthday.substring(e + 1, birthday.length()));
		final Dialog dialog = new DatePickerDialog(getActivity(), dateListener,
				year, month, day);
		dialog.setTitle("设置生日");
		dialog.show();
	}

	private void showSexDialog() {
		sexDialog = new SexSelectorDialog(getActivity(), R.style.MyDialog,
				new MyDialogListener() {

					@Override
					public void onClick(View view) {
						switch (view.getId()) {
						case R.id.dialog_btn_male:
							sex_tv.setText("男");
							user.setSex(sex_tv.getText().toString().trim());
							userChanged();
							sexDialog.dismiss();
							break;
						case R.id.dialog_btn_female:
							sex_tv.setText("女");
							userChanged();
							user.setSex(sex_tv.getText().toString().trim());
							sexDialog.dismiss();
							break;
						case R.id.dialog_btn_cancel:
							sexDialog.dismiss();
							break;
						}
					}
				});
		sexDialog.show();
	}

	private void logout() {
		Intent tent = new Intent(getActivity(), UserInfoActivity.class);
		User user = JSON.parseObject(
				PreferenceUtils.getPreferUserJson(getActivity()), User.class);
		PreferenceUtils.clearData(getActivity());
		PreferenceUtils.modifyStringValueInPreferences(
				PreferenceUtils.Phonenumber, user.getPhonenumber(),
				getActivity());
		getActivity().startActivity(tent);
		getActivity().finish();
	}

	public void savaUser() {
		if (isChanged
				&& NetConnectionUtil.isConnectWithTip(getActivity(),
						R.string.notConnectNet)) {
			UserService.trySaveUser(JSON.toJSONString(this.user),
					getResponseHandler(user, getActivity()), getActivity());
		}
	}

	private ResponseHandler getResponseHandler(final User info,
			final Context context) {
		if (mResponseHandler == null) {
			mResponseHandler = new ResponseHandler() {
				@Override
				public void onRequsetSucceeded(final Object data) {
					PreferenceUtils.modifyStringValueInPreferences(
							PreferenceUtils.User, JSON.toJSONString(info),
							context);
					Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
				}

				@Override
				public void onRequestFailed(final Object data) {
					Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
				}
			};
		}
		return mResponseHandler;
	}

	@Override
	public void onActivityResult(final int requestCode, final int resultCode,
			final Intent data) {
		if (resultCode != RESULT_CANCELED) {
			switch (requestCode) {
			case IMAGE_REQUEST_CODE:
			case RESULT_REQUEST_CODE:
				if (data != null) {
					getImageToView(data);
				}
				break;
			case IMAGE_REQUEST_CODE_KITKAT:
				mCurrentPhotoFile = new File(PhotoUtil.getPath(getActivity(),
						data.getData()));
				doCropPhoto(mCurrentPhotoFile);
				break;
			case CAMERA_REQUEST_CODE:
				doCropPhoto(mCurrentPhotoFile);
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void choosePhotoFromGallery() {
		Intent intent = new Intent();
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
			intent = getPhotoPickIntent();
			startActivityForResult(intent, IMAGE_REQUEST_CODE);
		} else {
			intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
			startActivityForResult(intent, IMAGE_REQUEST_CODE_KITKAT);
		}
	}

	private Intent getPhotoPickIntent() {
		final Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		return getCropIntent(intent);
	}

	private String getPhotoName() {
		return Calendar.getInstance().getTimeInMillis() + ".jpg";
	}

	private void doCropPhoto(final File f) {
		final Intent intent = getCropImageIntent(Uri.fromFile(f));
		startActivityForResult(intent, RESULT_REQUEST_CODE);
	}

	private Intent getCropImageIntent(final Uri photoUri) {
		final Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		return getCropIntent(intent);
	}

	private Intent getCropIntent(final Intent intent) {
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 320);
		intent.putExtra("outputY", 320);
		intent.putExtra("return-data", true);
		IMAGE_FILE_PATH = "/sdcard/MobileBank/" + getPhotoName();
		final File tempFile = new File(IMAGE_FILE_PATH); // 以时间秒为文件名
		final File temp = new File("/sdcard/MobileBank/");
		if (!temp.exists()) {
			temp.mkdir();
		}
		intent.putExtra("output", Uri.fromFile(tempFile));
		intent.putExtra("outputFormat", "JPEG");
		final Intent wrapperIntent = Intent.createChooser(intent, "选择图片");
		return wrapperIntent;
	}

	private void choosePhotoFromTakePhoto() {
		if (!PHOTO_DIR.exists()) {
			PHOTO_DIR.mkdirs();// 创建照片的存储目录
		}
		mCurrentPhotoFile = new File(PHOTO_DIR, getPhotoName());// 给新照的照片文件命名
		Log.i("URI", mCurrentPhotoFile.toString());
		IMAGE_FILE_PATH = mCurrentPhotoFile.toString();
		final Intent intent = getTakePickIntent(mCurrentPhotoFile);
		startActivityForResult(intent, CAMERA_REQUEST_CODE);
	}

	private static Intent getTakePickIntent(final File f) {
		final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}

	private void getImageToView(final Intent data) {
		final Bundle extras = data.getExtras();
		if (extras != null) {
			Bitmap photo = extras.getParcelable("data");
			avatar.setImageBitmap(photo);
			PreferenceUtils.modifyStringValueInPreferences(
					PreferenceUtils.AvatarPath, IMAGE_FILE_PATH, getActivity());
		}
	}
}
